﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace SynoManager.FileStation.Tasks
{
    public class DeleteTask : TaskBase
    {
        private readonly IRemoteLocation target;
        private readonly DirectoryInfo currentDirectory;
        private readonly string filename;

        public DeleteTask(IRemoteLocation target, DirectoryInfo currentDirectory)
        {
            this.target = target;
            this.currentDirectory = currentDirectory;
            this.filename = target.Name;
        }

        public override void Execute()
        {
            Debug.WriteLine("Deleting " + target.RelativePath, "DeleteTask");

            FileStationClient client = Queue.Service.client;
            var result = client.Delete(target.Path, currentDirectory.RelativePath);
            int pid = result.pid;
            Debug.WriteLine("Task sent to device, retrieved pid #" + pid + ", running = " + result.running, "DeleteTask");

            bool isRunning = result.running > 0;
            while (isRunning)
            {
                var progress = client.ReadDeleteProgress(pid);
                isRunning = progress.running > 0;

                Debug.WriteLine("#" + pid + ": " + progress.progress + " (running = " + progress.running + ")", "DeleteTask");

                if (!isRunning)
                {
                    OnProgressChanged(progress.progress);
                    Thread.Sleep(1000);
                }
            }

            OnCompleted();
        }

        public override string DisplayTitle
        {
            get { return "Delete " + filename; }
        }

        public override string DisplayDescription
        {
            get { return "To " + currentDirectory.RelativePath; }
        }

        public override System.Drawing.Image DisplayImage
        {
            get { return Properties.Resources.page_white_delete; }
        }
    }
}
